using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CPlatePrintSys.DataAccess.Context;
using CPlatePrintSys.DataAccess.Repositories;
using CPlatePrintSys.Domain.DTOs;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using CPlatePrintSys.Infrastructure.Repositories;

namespace CPlatePrintSys.Application.Services
{
    /// <summary>
    /// 数据同步服务 - 负责将外部数据源同步到数据库
    /// </summary>
    public class DataSyncService
    {
        private readonly IPlateAnnotationInfoRepository _plateAnnotationRepository;
        private readonly KmacsService _kmacsService;
        private readonly AmService _amService;
        private readonly CadWinService _cadWinService;
        private readonly ShipInfoService _shipInfoService;

        public DataSyncService(
            IPlateAnnotationInfoRepository plateAnnotationRepository,
            KmacsService kmacsService,
            AmService amService,
            CadWinService cadWinService,
            ShipInfoService shipInfoService)
        {
            _plateAnnotationRepository = plateAnnotationRepository;
            _kmacsService = kmacsService;
            _amService = amService;
            _cadWinService = cadWinService;
            _shipInfoService = shipInfoService;
        }

        /// <summary>
        /// 同步所有数据源到数据库（一次性同步，用于初始化）
        /// </summary>
        public async Task<DataSyncResult> SyncAllDataAsync()
        {
            var result = new DataSyncResult();
            
            try
            {
                // 1. 先同步Kmacs数据（基础数据）
                result.KmacsSyncResult = await SyncKmacsDataAsync();
                
                // 2. 同步AM数据（基于Kmacs数据进行关联）
                result.AmSyncResult = await SyncAmDataAsync();
                
                // 3. 同步CadWin数据（基于Kmacs数据进行关联）
                result.CadWinSyncResult = await SyncCadWinDataAsync();
                
                result.IsSuccess = true;
                result.Message = "数据同步完成";
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = $"数据同步失败: {ex.Message}";
                result.Exception = ex;
            }
            
            return result;
        }

        /// <summary>
        /// 分步骤同步：先同步Kmacs数据到数据库
        /// </summary>
        public async Task<SourceSyncResult> SyncKmacsDataOnlyAsync()
        {
            return await SyncKmacsDataAsync();
        }

        /// <summary>
        /// 分步骤同步：同步CadWin数据，基于已入库的Kmacs数据进行关联补充
        /// </summary>
        public async Task<SourceSyncResult> SyncCadWinDataOnlyAsync()
        {
            return await SyncCadWinDataAsync();
        }

        /// <summary>
        /// 分步骤同步：同步AM数据，基于已入库的Kmacs数据进行关联补充
        /// </summary>
        public async Task<SourceSyncResult> SyncAmDataOnlyAsync()
        {
            return await SyncAmDataAsync();
        }

        /// <summary>
        /// 同步Kmacs数据到数据库
        /// </summary>
        private async Task<SourceSyncResult> SyncKmacsDataAsync()
        {
            var result = new SourceSyncResult { SourceName = "Kmacs" };
            
            try
            {
                // 获取Kmacs数据
                var kmacsData = await _kmacsService.GetProcessInfosAsync();
                result.TotalRecords = kmacsData.Count;
                
                var addedCount = 0;
                var updatedCount = 0;
                
                foreach (var dto in kmacsData)
                {
                    var existingRecord = await _plateAnnotationRepository.GetByUniqueKeyAsync(
                        dto.StreamShipNo, dto.LotNo, dto.Sequence);
                    
                    if (existingRecord == null)
                    {
                        // 创建新记录
                        var newRecord = PlateAnnotationInfoFactory.FromKmacsDto(dto);
                        // 处理母船号和流用船号的关系维护
                        await UpdateMotherShipRelationship(newRecord, dto.StreamShipNo);
                        await _plateAnnotationRepository.AddAsync(newRecord);
                        addedCount++;
                    }
                    else
                    {
                        // 更新现有记录（仅更新Kmacs相关字段）
                        await UpdateKmacsFields(existingRecord, dto);
                        await _plateAnnotationRepository.UpdateAsync(existingRecord);
                        updatedCount++;
                    }
                }
                
                result.AddedRecords = addedCount;
                result.UpdatedRecords = updatedCount;
                result.IsSuccess = true;
                result.Message = $"Kmacs数据同步完成: 新增{addedCount}条, 更新{updatedCount}条";
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = $"Kmacs数据同步失败: {ex.Message}";
                result.Exception = ex;
            }
            
            return result;
        }

        /// <summary>
        /// 同步AM数据到数据库（基于Kmacs数据进行关联）
        /// </summary>
        private async Task<SourceSyncResult> SyncAmDataAsync()
        {
            var result = new SourceSyncResult { SourceName = "AM" };
            
            try
            {
                // 获取AM数据
                var amData = await _amService.GetDrawingInfosAsync();
                result.TotalRecords = amData.Count;
                
                var addedCount = 0;
                var updatedCount = 0;
                
                foreach (var dto in amData)
                {
                    // 根据船号、LOT号、加工序列查找对应的Kmacs记录
                    var existingRecord = await _plateAnnotationRepository.GetByUniqueKeyAsync(
                        dto.ShipNo, dto.LotNo, dto.Sequence);
                    
                    if (existingRecord == null)
                    {
                        // 如果没有对应的Kmacs记录，创建新的AM记录
                        var newRecord = PlateAnnotationInfoFactory.FromAmDto(dto);
                        // 处理母船号和流用船号的关系维护
                        await UpdateMotherShipRelationship(newRecord, dto.ShipNo);
                        await _plateAnnotationRepository.AddAsync(newRecord);
                        addedCount++;
                    }
                    else
                    {
                        // 更新现有记录（补充AM相关字段）
                        UpdateAmFields(existingRecord, dto);
                        await _plateAnnotationRepository.UpdateAsync(existingRecord);
                        updatedCount++;
                    }
                }
                
                result.AddedRecords = addedCount;
                result.UpdatedRecords = updatedCount;
                result.IsSuccess = true;
                result.Message = $"AM数据同步完成: 新增{addedCount}条, 更新{updatedCount}条";
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = $"AM数据同步失败: {ex.Message}";
                result.Exception = ex;
            }
            
            return result;
        }

        /// <summary>
        /// 同步CadWin数据到数据库（基于Kmacs数据进行关联）
        /// </summary>
        private async Task<SourceSyncResult> SyncCadWinDataAsync()
        {
            var result = new SourceSyncResult { SourceName = "CadWin" };
            
            try
            {
                // 获取CadWin数据
                var cadWinData = await _cadWinService.GetDrawingInfosAsync();
                result.TotalRecords = cadWinData.Count;
                
                var addedCount = 0;
                var updatedCount = 0;
                
                foreach (var dto in cadWinData)
                {
                    // 根据船号、LOT号、加工序列查找对应的记录
                    var existingRecord = await _plateAnnotationRepository.GetByUniqueKeyAsync(
                        dto.ShipNo, dto.LotNo, dto.Sequence);
                    
                    if (existingRecord == null)
                    {
                        // 如果没有对应记录，创建新的CadWin记录
                        var newRecord = PlateAnnotationInfoFactory.FromCadWinDto(dto);
                        // 处理母船号和流用船号的关系维护
                        await UpdateMotherShipRelationship(newRecord, dto.ShipNo);
                        await _plateAnnotationRepository.AddAsync(newRecord);
                        addedCount++;
                    }
                    else
                    {
                        // 更新现有记录（补充CadWin相关字段）
                        UpdateCadWinFields(existingRecord, dto);
                        await _plateAnnotationRepository.UpdateAsync(existingRecord);
                        updatedCount++;
                    }
                }
                
                result.AddedRecords = addedCount;
                result.UpdatedRecords = updatedCount;
                result.IsSuccess = true;
                result.Message = $"CadWin数据同步完成: 新增{addedCount}条, 更新{updatedCount}条";
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = $"CadWin数据同步失败: {ex.Message}";
                result.Exception = ex;
            }
            
            return result;
        }

        /// <summary>
        /// 更新Kmacs相关字段
        /// </summary>
        private async Task UpdateKmacsFields(PlateAnnotationInfo record, KmacsProcessInfoDto dto)
        {
            record.SheetConsistentNo = dto.SheetConsistentNo;
            record.CNO = dto.CNO;
            record.MergedInfo = dto.MergedInfo;
            record.SheetSpecCls = dto.SheetSpecCls;
            record.SheetSpecThickness = dto.SheetSpecThickness;
            record.SheetSpecLength = dto.SheetSpecLength;
            record.SheetSpecWidth = dto.SheetSpecWidth;
            record.PlanUsedDate = dto.PlanUsedDate;
            
            // 处理母船号和流用船号的关系维护
            await UpdateMotherShipRelationship(record, dto.StreamShipNo);
            
            // 如果SourceType为空，设置为KMACS
            if (record.SourceType == 0) // 默认值为KMACS
            {
                record.SourceType = SourceType.KMACS;
            }
        }

        /// <summary>
        /// 更新母船号和流用船号的关系
        /// 规则：如果流用船有母船则补充完整，没有保持为空（可能自身就是母船）
        /// </summary>
        private async Task UpdateMotherShipRelationship(PlateAnnotationInfo record, string streamShipNo)
        {
            if (string.IsNullOrEmpty(streamShipNo))
            {
                record.MotherShipNo = null;
                return;
            }

            try
            {
                // 获取流用船号到母船号的映射关系
                var streamShipToMotherShipMap = await _shipInfoService.GetStreamShipToMotherShipMapAsync();
                
                // 如果流用船有对应的母船，则设置母船号
                if (streamShipToMotherShipMap.ContainsKey(streamShipNo))
                {
                    record.MotherShipNo = streamShipToMotherShipMap[streamShipNo];
                }
                else
                {
                    // 如果流用船没有对应的母船，保持为空（可能自身就是母船）
                    record.MotherShipNo = null;
                }
            }
            catch (Exception ex)
            {
                // 如果获取船号关系失败，记录错误但不影响数据同步
                System.Diagnostics.Debug.WriteLine($"获取船号关系失败: {ex.Message}");
                record.MotherShipNo = null;
            }
        }

        /// <summary>
        /// 更新AM相关字段
        /// </summary>
        private void UpdateAmFields(PlateAnnotationInfo record, AmDrawingInfoDto dto)
        {
            record.PlateNo = dto.PlateNo;
            record.DesignSpecCls = dto.DesignSpecCls;
            record.DesignSpecThickness = dto.DesignSpecThickness;
            record.DesignSpecLength = dto.DesignSpecLength;
            record.DesignSpecWidth = dto.DesignSpecWidth;
            record.DesignDrawingPath = dto.SdbPath;
            
            // 设置布局模式
            record.LayoutMean = dto.MFlag == 1 ? LayoutMean.MirrorLayout : LayoutMean.Unprocessed;
            
            // 如果当前SourceType是KMACS，保持KMACS；否则设置为AM
            if (record.SourceType == 0) // 默认值为AM
            {
                record.SourceType = SourceType.AM;
            }
        }

        /// <summary>
        /// 更新CadWin相关字段
        /// </summary>
        private void UpdateCadWinFields(PlateAnnotationInfo record, CadWinDrawingInfoDto dto)
        {
            record.PlateNo = dto.PlateNo;
            record.DesignSpecCls = dto.DesignSpecCls;
            record.DesignSpecThickness = dto.DesignSpecThickness;
            record.DesignSpecLength = dto.DesignSpecLength;
            record.DesignSpecWidth = dto.DesignSpecWidth;
            record.DesignDrawingPath = dto.DxfPath;
            
            // 如果当前SourceType是KMACS或AM，保持；否则设置为CadWin
            if (record.SourceType == 0) // 默认值为CadWin
            {
                record.SourceType = SourceType.CadWin;
            }
        }

        /// <summary>
        /// 获取数据库中的标注信息（用于ProcessSequenceView）
        /// </summary>
        public async Task<List<PlateAnnotationInfo>> GetPlateAnnotationInfosAsync()
        {
            return (await _plateAnnotationRepository.GetAllAsync()).ToList();
        }

        /// <summary>
        /// 根据条件查询标注信息
        /// </summary>
        public async Task<List<PlateAnnotationInfo>> GetPlateAnnotationInfosAsync(
            string streamShipNo = null, 
            string lotNo = null, 
            string sequence = null,
            DateTime? planUsedDateStart = null,
            DateTime? planUsedDateEnd = null)
        {
            var query = await _plateAnnotationRepository.GetAllAsync();
            
            if (!string.IsNullOrEmpty(streamShipNo) && streamShipNo != "全部")
            {
                query = query.Where(x => x.StreamShipNo == streamShipNo);
            }
            
            if (!string.IsNullOrEmpty(lotNo) && lotNo != "全部")
            {
                query = query.Where(x => x.LotNo == lotNo);
            }
            
            if (!string.IsNullOrEmpty(sequence) && sequence != "全部")
            {
                query = query.Where(x => x.Sequence == sequence);
            }
            
            if (planUsedDateStart.HasValue)
            {
                query = query.Where(x => x.PlanUsedDate >= planUsedDateStart.Value);
            }
            
            if (planUsedDateEnd.HasValue)
            {
                query = query.Where(x => x.PlanUsedDate <= planUsedDateEnd.Value);
            }
            
            return query.ToList();
        }

        /// <summary>
        /// 更新标注信息的布局信息
        /// </summary>
        public async Task UpdateLayoutInfoAsync(int id, LayoutMean layoutMean, string layoutInfo)
        {
            var record = await _plateAnnotationRepository.GetByIdAsync(id);
            if (record != null)
            {
                record.LayoutMean = layoutMean;
                record.LayoutInfo = layoutInfo;
                await _plateAnnotationRepository.UpdateAsync(record);
            }
        }

        /// <summary>
        /// 更新标注信息的合并信息
        /// </summary>
        public async Task UpdateMergedInfoAsync(int id, string mergedInfo)
        {
            var record = await _plateAnnotationRepository.GetByIdAsync(id);
            if (record != null)
            {
                record.MergedInfo = mergedInfo;
                await _plateAnnotationRepository.UpdateAsync(record);
            }
        }

        /// <summary>
        /// 批量更新标注生成状态
        /// </summary>
        public async Task UpdateAnnotationGeneratedStatusAsync(List<int> ids, bool isGenerated)
        {
            foreach (var id in ids)
            {
                var record = await _plateAnnotationRepository.GetByIdAsync(id);
                if (record != null)
                {
                    record.IsAnnotationGenerated = isGenerated;
                    await _plateAnnotationRepository.UpdateAsync(record);
                }
            }
        }

        /// <summary>
        /// 更新母船号时同步更新相关标注信息
        /// </summary>
        public async Task<int> UpdateMotherShipNoInAnnotationsAsync(string oldMotherShipNo, string newMotherShipNo)
        {
            return await _plateAnnotationRepository.UpdateMotherShipNoAsync(oldMotherShipNo, newMotherShipNo);
        }

        /// <summary>
        /// 更新流用船号时同步更新相关标注信息
        /// </summary>
        public async Task<int> UpdateStreamShipNoInAnnotationsAsync(string oldStreamShipNo, string newStreamShipNo)
        {
            return await _plateAnnotationRepository.UpdateStreamShipNoAsync(oldStreamShipNo, newStreamShipNo);
        }

        /// <summary>
        /// 删除母船时同步删除相关标注信息
        /// </summary>
        public async Task<int> DeleteAnnotationsByMotherShipNoAsync(string motherShipNo)
        {
            return await _plateAnnotationRepository.DeleteByMotherShipNoAsync(motherShipNo);
        }

        /// <summary>
        /// 删除流用船时同步删除相关标注信息
        /// </summary>
        public async Task<int> DeleteAnnotationsByStreamShipNoAsync(string streamShipNo)
        {
            return await _plateAnnotationRepository.DeleteByStreamShipNoAsync(streamShipNo);
        }
    }

    /// <summary>
    /// 数据同步结果
    /// </summary>
    public class DataSyncResult
    {
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        public Exception Exception { get; set; }
        public SourceSyncResult KmacsSyncResult { get; set; }
        public SourceSyncResult AmSyncResult { get; set; }
        public SourceSyncResult CadWinSyncResult { get; set; }
    }

    /// <summary>
    /// 单个数据源同步结果
    /// </summary>
    public class SourceSyncResult
    {
        public string SourceName { get; set; }
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        public Exception Exception { get; set; }
        public int TotalRecords { get; set; }
        public int AddedRecords { get; set; }
        public int UpdatedRecords { get; set; }
    }
}
